<?php

namespace App\Jobs;

use App\Http\Controllers\Wechat\ServerController;
use App\Models\FleaWithdrawal;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class FleaUserWithdrawal implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $id;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 5;

    /**
     * Create a new job instance.
     * @param $id int 跳转市场用户提现的ID
     * @return void
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $id = $this->id;
            $data = FleaWithdrawal::query()->where('id', $id)->firstOrFail();
            //通过用户ID查询用户的openid
            $openid = User::query()->where('id', $data->user_id)->value('openid');
            $order_sn = 'FleaTx' . makeOrderSn();
            //微信的单位是分
            $amount = $data->money * 100;
            $res = ServerController::payment($openid, $order_sn, $amount);

            if ($res === true) {
                //success
                //提现记录修改成提现成功
                FleaWithdrawal::query()->where('id', $this->id)->update([
                    'pay_time' => $res['微信返回的时间'],
                    'is_pay' => 1,
                    'order_sn' => $order_sn
                ]);

            } else {
                //记录失败原因
                FleaWithdrawal::query()->where('id', $this->id)->update([
                    'msg' => $res
                ]);
            }
        } catch (\Exception $exception) {
            $this->release(5);
            dump('抛出异常');
            echo $exception->getMessage();
        }

    }

    /**
     * 任务未能处理
     *
     * @param \Exception $exception
     * @return void
     */
    public function failed(\Exception $exception)
    {
        dump('任务失败：' . $exception->getMessage());
    }

}
